package model

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"service/conf"

	"gitee.com/cloudapex/ulern/htp"
)

type Department struct {
	Id       int64  `json:"id"`
	Name     string `json:"name"`
	ParentId int64  `json:"parentid"`
	Order    int64  `json:"order"`
}
type ResDepInfo struct {
	ErrCode int64  `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
	Id      int64  `json:"id"`
}

/**
 * 请求方式：POST（HTTPS）
 * 请求地址：https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=ACCESS_TOKEN
 * 请求包体：
 */

func (this *Department) AddFram() (depar Department, err error) {

	//添加组织架构
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		err = err
		return
	}

	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=%s", token)
	bodyStruct := map[string]interface{}{
		"name":     this.Name,
		"parentid": this.ParentId,
	}

	body, err := json.Marshal(bodyStruct)
	if err != nil {
		err = err
		fmt.Println("Marshal msg err", err)
		return
	}
	//
	rsp, err := htp.HttpRequest("POST", url, string(body), func(h http.Header) { h.Add("Content-Type", "application/json") })
	if err != nil {
		err = err
		fmt.Println("Marshal msg err", err)
		return
	}

	var res ResDepInfo
	err = json.Unmarshal(rsp.Body, &res)
	if err != nil {
		log.Println("GetDepartmentUsers Unmarshal err=", err)
	}
	this.Id = res.Id
	wxList, err := this.GetDeparList()

	var wxRes Department
	if len(wxList) > 0 {
		wxRes = wxList[0]
	}
	return wxRes, err
}

/**
 *  请求方式 GET
 *  access_token	是	调用接口凭证
 *  id	否	部门id。获取指定部门及其下的子部门（以及及子部门的子部门等等，递归）。 如果不填，默认获取全量组织架构
 */

type WxDepartList struct {
	WxList  []Department `json:"department"`
	ErrCode int64        `json:"errcode"`
	ErrMsg  string       `json:"errmsg"`
}

func (this *Department) GetDeparList() (wxList []Department, err error) {
	//获取组织架构列表
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		err = err
		return
	}

	var url string
	if this.Id == 0 {
		url = fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s", token)
	} else {
		url = fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s&id=%d", token, this.Id)
	}

	rsp, err := htp.HttpRequest("GET", url, "", nil)
	if err != nil {
		return nil, err
	}

	var list WxDepartList
	err = json.Unmarshal(rsp.Body, &list)
	if err != nil {
		log.Println("GetDepartmentUsers Unmarshal err=", err)
	}
	return list.WxList, err
}

/**
 * 请求方式：GET（HTTPS）
 * 请求地址：https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=ACCESS_TOKEN&id=ID
 * 参数说明 ：id  部门id。（注：不能删除根部门；不能删除含有子部门、成员的部门）
 */
func (this *Department) DelFram() (id int64, err error) {
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		err = err
		return
	}
	//删除组织架构
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=%s&id=%d", token, this.Id)
	rsp, err := htp.HttpRequest("GET", url, "", nil)
	if err != nil {
		err = err
		return
	}

	var res ResDepInfo
	err = json.Unmarshal(rsp.Body, &res)
	if err != nil {
		log.Println("GetDepartmentUsers Unmarshal err=", err)
	}
	if res.ErrCode == 0 {
		fmt.Println("删除架构成功:", res.Id)
	} else {
		fmt.Println("删除架构失败:", res.ErrMsg)
	}
	return res.Id, err
}

/**
 *  请求方式：POST（HTTPS）
 *  请求地址：https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=ACCESS_TOKEN
 *  请求包体（如果非必须的字段未指定，则不更新该字段）：
 */
func (this *Department) UpdateFram() error {
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		return err
	}

	//更新组织架构
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=%s", token)

	bodyStruct := map[string]interface{}{
		"name": this.Name,
		"id":   this.Id,
	}

	body, err := json.Marshal(bodyStruct)
	if err != nil {
		fmt.Println("Marshal msg err", err)
		return err
	}

	//
	rsp, err := htp.HttpRequest("POST", url, string(body), func(h http.Header) { h.Add("Content-Type", "application/json") })
	if err != nil {
		fmt.Println("HttpRequest err", err)
		return err
	}

	var res ResDepInfo
	err = json.Unmarshal(rsp.Body, &res)
	if err != nil {
		log.Println("GetDepartmentUsers Unmarshal err=", err)
	}

	if res.ErrCode == 0 {
		fmt.Println("更新架构成功:", res.Id)
	} else {
		fmt.Println("更新架构失败:", res.ErrMsg)
	}
	return err
}

func (this *Department) UpdateFramOrder() error {
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		return err
	}
	//更新组织架构
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=%s", token)

	bodyStruct := map[string]interface{}{
		"id":    this.Id,
		"order": this.Order,
	}

	body, err := json.Marshal(bodyStruct)
	if err != nil {
		fmt.Println("Marshal msg err", err)
		return err
	}
	//
	rsp, err := htp.HttpRequest("POST", url, string(body), func(h http.Header) { h.Add("Content-Type", "application/json") })
	if err != nil {
		fmt.Println("HttpRequest err", err)
		return err
	}

	var res ResDepInfo
	err = json.Unmarshal(rsp.Body, &res)
	if err != nil {
		log.Println("GetDepartmentUsers Unmarshal err=", err)
	}

	if res.ErrCode == 0 {
		fmt.Println("更新架构成功:", res.Id)
	} else {
		fmt.Println("更新架构失败:", res.ErrMsg)
	}
	return err
}

//------------------------------------------------------------------------------
type WorkWeixin struct {
	CorpId     string `json:"corpid"`
	CorpSecret string `json:"corpsecret"`
	Url        string `json:"url"`
	//agentId 表示应用id， 0  表示本应用
	agentId     int
	userMobiles map[string]string
}
type Tag struct {
	TagName string `json:"tagname"`
	TagId   int    `json:"tagid"`
}
type tags struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	TagList []Tag  `json:"taglist"`
}
type departments struct {
	Errcode    int          `json:"errcode"`
	Errmsg     string       `json:"errmsg"`
	Department []Department `json:"department"`
}

type users struct {
	Errcode  int    `json:"errcode"`
	Errmsg   string `json:"errmsg"`
	Userlist []User `json:"userlist"`
}

type User struct {
	Userid       string `json:"userid"`
	Name         string `json:"name"`
	Department   []int  `json:"department"`
	Mobile       string `json:"mobile"`
	Email        string `json:"email"`
	Status       int    `json:"status"`
	Avatar       string `json:"avatar"`
	Telephone    string `json:"telephone"`
	English_name string `json:"english_name"`
}

func (this *WorkWeixin) GetDepartmentParentList() ([]Department, error) {
	return this.getDepartmentList(1)
}

func (this *WorkWeixin) GetSonDepartmentParentList(sonDepartment int) ([]Department, error) {
	return this.getDepartmentList(sonDepartment)
}

//获取部门成员
func (this *WorkWeixin) getDepartmentList(sonDepartment int) ([]Department, error) {
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s&id=%d", token, sonDepartment)
	rsp, err := htp.HttpRequest("GET", url, "", nil)
	if err != nil {
		return nil, err
	}
	var f departments
	err = json.Unmarshal(rsp.Body, &f)
	if err != nil {
		log.Println("getDepartmentList Unmarshal err=", err)
	}

	log.Println(f)
	return f.Department, nil
}

//department_id 部门id
//fetch_child 1/0：是否递归获取子部门下面的成员
func (this *WorkWeixin) GetDepartmentUsers(department_id int, fetch_child int) []User {
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		return nil
	}
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=%s&department_id=%d&fetch_child=%d",
		token, department_id, fetch_child)
	rsp, err := htp.HttpRequest("GET", url, "", nil)
	if err != nil {
		return nil
	}

	var f users
	err = json.Unmarshal(rsp.Body, &f)
	if err != nil {
		log.Println("GetDepartmentUsers Unmarshal err=", err)
	}

	return f.Userlist
}

//参数	必须		说明
//access_token	是	调用接口凭证
//tagname	是	标签名称，长度限制为32个字（汉字或英文字母），标签名不可与其他标签重名。
//tagid	否	标签id，非负整型，指定此参数时新增的标签会生成对应的标签id，不指定时则以目前最大的id自增。
func (this *WorkWeixin) CreateTag(tag Tag) {
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		return
	}
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token=%s", token)

	body, err := json.Marshal(tag)
	if err != nil {
		fmt.Println("Marshal msg err", err)
		return
	}
	//
	rsp, err := htp.HttpRequest("POST", url, string(body), func(h http.Header) { h.Add("Content-Type", "application/json") })
	if err != nil {
		err = err
		fmt.Println("HttpRequest err", err)
		return
	}

	log.Println("CreateTag Unmarshal err=", err, string(rsp.Body))

}

//获取标签
func (this *WorkWeixin) GetTagList() []Tag {
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		return nil
	}
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token=%s", token)

	rsp, err := htp.HttpRequest("GET", url, "", nil)
	if err != nil {
		return nil
	}

	var f tags
	err = json.Unmarshal(rsp.Body, &f)
	if err != nil {
		log.Println("GetDepartmentUsers Unmarshal err=", err)
	}
	return f.TagList
}
func (this *WorkWeixin) GetTagUser(tagid int) []User {
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		return nil
	}
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/tag/get?access_token=%s&tagid=%d", token, tagid)

	rsp, err := htp.HttpRequest("GET", url, "", nil)
	if err != nil {
		return nil
	}

	var f users
	err = json.Unmarshal(rsp.Body, &f)
	if err != nil {
		log.Println("GetTagUser Unmarshal err=", err)
	}
	return f.Userlist
}

//添加标签成员
func (this *WorkWeixin) AddTagUsers(userIds []string, tagId int) string {
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		return ""
	}
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers?access_token=%s", token)

	bodyStruct := map[string]interface{}{
		"tagid":    tagId,
		"userlist": userIds,
	}

	body, err := json.Marshal(bodyStruct)
	log.Println("json", string(body))
	if err != nil {
		fmt.Println("Marshal msg err", err)
		return fmt.Sprint(err)
	}
	//
	rsp, err := htp.HttpRequest("POST", url, string(body), func(h http.Header) { h.Add("Content-Type", "application/json") })
	if err != nil {
		err = err
		fmt.Println("HttpRequest err", err)
		return ""
	}

	return string(rsp.Body)
}
func (this *WorkWeixin) SendText(toUser string, toparties string, totag string, text string) string {
	token, err := conf.Wechat.GetAccessToken()
	if err != nil {
		return ""
	}
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", token)

	log.Println("send msg=", text)
	bodyStruct := map[string]interface{}{
		"touser":  toUser,
		"toparty": toparties,
		"totag":   totag,
		"msgtype": "text",
		"agentid": this.agentId,
		"text": map[string]interface{}{
			"content": text,
		},
	}

	body, err := json.Marshal(bodyStruct)

	if err != nil {
		fmt.Println("Marshal msg err", err)
		return "Marshal msg err"
	}
	log.Println(string(body))
	//
	rsp, err := htp.HttpRequest("POST", url, string(body), func(h http.Header) { h.Add("Content-Type", "application/json") })
	if err != nil {
		fmt.Println("HttpRequest err", err)
		return ""
	}

	log.Println(string(rsp.Body))
	return string(rsp.Body)
}
func (this *WorkWeixin) GetUserIdByMobile(mobile string) string {
	if this.userMobiles == nil {
		this.userMobiles = make(map[string]string)
		for _, v := range this.GetDepartmentUsers(1, 1) {
			this.userMobiles[v.Mobile] = v.Userid
		}
	}
	return this.userMobiles[mobile]
}
